<?php

class Domain {

	private $id;
	private $created_at;
	private $updated_at;

	public $domain;
	public $local;

	function __construct($id) {
		$this->id = $id;
	}	

	public function getID() {
		return $this->id;
	}



	public function domains() {
	
		$db_connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
		
		$q = "SELECT * FROM domains";
		
		$testDomains = array();
		$domains = array();
		
		if($result = mysqli_query($db_connection, $q)) {
			while($row = mysqli_fetch_assoc($result)) {
				array_push($testDomains, $row);
			}
		}
	
		foreach($testDomains as $row) {
			$testDomain = new Domain($row['domain_id']);
			$testDomain->created_at = $row['domain_created_at'];
			$testDomain->domain = $row['domain_domain'];
			$testDomain->updated_at = $row['domain_updated_at'];
			$testDomain->local = $row['domain_local'];

			array_push($domains, $testDomain);
		}	

		return $domains;
	}
	
	
	
	public function get_domain($id) {
		
		$db_connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
		
		$result = mysqli_query($db_connection, "SELECT * FROM domains WHERE domain_id = $id LIMIT 0,1");
		$domain = mysqli_fetch_assoc($result);
			
		$testDomain = new Domain($domain['domain_id']);
		$testDomain->created_at = $domain['domain_created_at'];
		$testDomain->domain = $domain['domain_domain'];
		$testDomain->updated_at = $domain['domain_updated_at'];
		$testDomain->local = $domain['domain_local'];

		return $testDomain; 
		
	}
	
	
	public function new_domain($domain, $local) {
	
		$db_connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
		
		$stmt = mysqli_prepare($db_connection, "INSERT INTO domains (domain_domain, domain_local) VALUES (?, ?)");
		mysqli_stmt_bind_param($stmt, "si", $domain, $local);
		mysqli_stmt_execute($stmt);
	
		// Retrieve new record
		$id = $stmt->insert_id;
		
		$domain = Domain::get_domain($id);
		
		mysqli_stmt_close($stmt);
		
		return $domain;
	
	}
	
	
	public function update_domain($id, $domain, $local) {
	
		$db_connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
		
		$stmt = mysqli_prepare($db_connection, "UPDATE domains SET domain_domain = ?, domain_local = ? WHERE domain_id = ?");
		mysqli_stmt_bind_param($stmt, "sii", $domain, $local, $id);
		mysqli_stmt_execute($stmt);
	
		// Retrieve new record
		$id = $stmt->insert_id;
		
		$domain = Domain::get_domain($id);
		
		mysqli_stmt_close($stmt);
		
		return $domain;
	
	}
	
	
	public function remove_domain($id) {
	
		$db_connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);

		mysqli_query($db_connection, "DELETE FROM domains WHERE domain_id = $id");		
		//printf("%d Row deleted.\n", $mysqli->affected_rows);
	
	}

}

?>
